package com.e.library.http;

import android.content.Context;
import android.content.Intent;

import com.google.gson.JsonParseException;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * http回调
 * Created by lxy on 2017/6/29 21:52.
 */
public abstract class EObserver implements Observer<EResponse> {

    abstract public void successful(EResponse response);
    abstract public void failure(String msg);

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(EResponse response) {
        onComplete();
        if (response.successful()) {
            successful(response);
        }else {
            failure(response.message());
        }
//        onComplete();
//        if (response.successful()) {
//            successful(response);
//        }else if (response.toLogin()){
//            Context context = EClient.with().app();
//            if (context != null){
//                toLoginActivity(context);
//            }else {
//                failure(response.message());
//            }
//
//        } else {
//            failure(response.message());
//        }
    }

    @Override
    public void onError(Throwable e) {
        onComplete();
        if (e instanceof SessionExpireException){
        }else {
            failure(exception(e));
        }
    }

    @Override
    public void onComplete() {

    }


    private void toLoginActivity(Context context){
        try {
            Intent intent = new Intent();
            intent.setClassName(context,"com.wedo.mall.activity.LoginActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            failure(exception(e));
        }
    }

    public static String exception(Throwable t){
        String msg = "系统发生错误";
        if (t instanceof TimeoutException || t instanceof SocketTimeoutException){
            msg = "请求超时了，请稍后再试";
        }else if (t instanceof UnknownHostException){
            msg = "无法访问，服务器出错了";
        }else if (t instanceof NullPointerException){
            msg = "请重新登录再试！";
        }else if (t instanceof IOException){
            msg = "网络异常，请稍后再试";
        }else if (t instanceof JsonParseException){
            msg = "数据解析出错了";
        }else if (t instanceof ClassCastException){
            msg = "数据解析出错了";
        }
        return msg;
    }
}
